<script setup lang="ts">
import { EditorPlain, EditorMarkdown } from "#components";

const saveContentTimer = ref<number>();
const saveContentStatus = ref<"Syncing" | "Synced">();
const saveContentMsg = ref("已自动保存");

const frm = reactive<NoteBase>({
  content: "",
  is_md: false,
  has_view_pwd: false,
  view_pwd: "",
  has_man_pwd: false,
  man_pwd: "",
});
const originPwd = reactive({ view: false, man: false });

const clearPwdDialog = reactive({ view: false, man: false });

const { id: idParam } = useRoute().params;
const id = computed(() => idParam.toString());
const { $get, $post } = use$fetch();

const loadData = async () => {
  await $get<Note>(`/${id.value}`, (v) => {
    Object.assign(frm, { ...v, view_pwd: "", man_pwd: "" });
    originPwd.view = v?.has_view_pwd || false;
    originPwd.man = v?.has_man_pwd || false;
    return v;
  });
};

const saveContent = async () => {
  saveContentStatus.value = "Syncing";
  const data = {
    ...frm,
    has_view_pwd: originPwd.view ? originPwd.view : frm.view_pwd ? true : false,
    has_man_pwd: originPwd.man ? originPwd.man : frm.man_pwd ? true : false,
  };
  await $post<AffResp>(
    `/${id.value}`,
    data,
    (v) => {
      saveContentStatus.value = "Synced";
      return v;
    },
    true
  );
};

const handleSaveClick = async () => {
  saveContentMsg.value = "已保存";
  await saveContent();
};

onMounted(async () => {
  await loadData();
});

onMounted(() => {
  saveContentTimer.value = window.setInterval(async () => {
    saveContentMsg.value = "已自动保存";
    await saveContent();
  }, 60000);
});

onUnmounted(() => {
  clearInterval(saveContentTimer.value);
});
</script>

<template>
  <header class="bg-white/50">
    <nav class="container mx-auto flex justify-between items-center p-3">
      <NuxtLink to="/" class="flex justify-start items-center gap-x-2">
        <div><img src="/logo.png" class="w-6 object-cover" /></div>
        <h2 class="text-lg">记事本</h2>
      </NuxtLink>

      <div class="flex justify-start items-center gap-x-4">
        <div
          v-if="saveContentStatus"
          class="flex justify-start items-center gap-x-1 text-xs rounded text-white p-0.5"
          :class="{
            'bg-green-600': saveContentStatus === 'Synced',
            'bg-orange-600': saveContentStatus === 'Syncing',
          }"
        >
          <Icon
            name="uil:sync"
            :class="{ 'animate-spin': saveContentStatus === 'Syncing' }"
          />
          <div v-if="saveContentStatus === 'Synced'">{{ saveContentMsg }}</div>
          <div v-else>正在自动保存</div>
        </div>
        <ul class="flex justify-start items-center gap-x-3">
          <li>
            <NuxtLink
              to="/"
              class="flex justify-start items-center gap-x-1 rounded-md px-1.5 py-0.5 hover:bg-white/50"
            >
              <Icon name="uil:file-plus" size="1rem" />
              <div>新建</div>
            </NuxtLink>
          </li>
          <li>
            <button
              class="flex justify-start items-center gap-x-1 rounded-md px-1.5 py-0.5 hover:bg-white/50"
              @click="handleSaveClick"
              :disabled="saveContentStatus === 'Syncing'"
            >
              <Icon name="uil:save" size="1rem" />
              <div>保存</div>
            </button>
          </li>
        </ul>
      </div>
    </nav>
  </header>

  <main class="container mx-auto my-3 flex flex-col gap-y-3 px-3 lg:flex-col">
    <div class="flex justify-end items-center text-sm text-gray-600 gap-x-6">
      <!-- <label
        class="flex flex-col justify-start items-center gap-y-1 lg:gap-y-0 lg:gap-x-2 lg:flex-row relative"
      >
        <div>访问密码</div>
        <div class="bg-white/50 rounded py-0.5 px-1">
          <input
            class="outline-none bg-transparent block w-full"
            type="password"
            :placeholder="`${
              frm.has_view_pwd ? '留空不修改密码' : '留空所有人可查看'
            }`"
            v-model="frm.view_pwd"
          />
        </div>
        <div
          v-if="originPwd.view"
          class="absolute left-[5.5rem] top-0 text-green-600 px-0.5 py-0 lg:-left-4 lg:top-0.5"
        >
          <button @click="clearPwdDialog.view = true">
            <Icon name="uil:trash" class="-mb-0.5" />
          </button>
        </div>
      </label>
      <label
        class="flex flex-col justify-start items-center gap-y-1 lg:gap-y-0 lg:gap-x-2 lg:flex-row relative"
      >
        <div>管理密码</div>
        <div class="bg-white/50 rounded py-0.5 px-1">
          <input
            class="outline-none bg-transparent block w-full"
            type="password"
            :placeholder="`${
              frm.has_man_pwd ? '留空不修改密码' : '留空不可管理操作'
            }`"
            v-model="frm.man_pwd"
          />
        </div>
        <div
          v-if="originPwd.man"
          class="absolute left-[5.5rem] top-0 text-green-600 px-0.5 py-0 lg:-left-4 lg:top-0.5"
        >
          <button @click="clearPwdDialog.man = true">
            <Icon name="uil:trash" class="-mb-0.5" />
          </button>
        </div>
      </label> -->
      <button
        class="flex justify-start flex-row gap-x-1 items-center"
        @click="frm.is_md = !frm.is_md"
      >
        <div :class="{ 'text-gray-800': !frm.is_md }">纯文本</div>
        <Icon
          name="uil:toggle-off"
          size="1.5rem"
          :class="{ 'text-blue-500 rotate-180': frm.is_md }"
        />
        <div :class="{ 'text-blue-500 ': frm.is_md }">Markdown</div>
      </button>
    </div>

    <div class="editor-container">
      <component
        :is="frm.is_md ? EditorMarkdown : EditorPlain"
        v-model="frm.content"
      />
    </div>
  </main>

  <DailogConfirm
    key="clearViewPwdDialog"
    v-if="clearPwdDialog.view"
    @cancel="clearPwdDialog.view = false"
    @ok="
      () => {
        frm.has_view_pwd = false;
        frm.view_pwd = '';
        clearPwdDialog.view = false;
        originPwd.view = false;
      }
    "
    >确定清空访问密码？</DailogConfirm
  >
  <DailogConfirm
    key="clearManPwdDialog"
    v-if="clearPwdDialog.man"
    @cancel="clearPwdDialog.man = false"
    @ok="
      () => {
        frm.has_man_pwd = false;
        frm.man_pwd = '';
        clearPwdDialog.man = false;
        originPwd.man = false;
      }
    "
    >确定清空访问密码？</DailogConfirm
  >
</template>

<style scoped>
.editor-container {
  height: calc(100vh - 7rem);
  @apply rounded-md overflow-hidden;
}
</style>
